package com.tfd.blog.controller;

import com.tfd.blog.domain.Login;
import com.tfd.blog.filter.NeedLogin;
import com.tfd.blog.utlis.JsonResult;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author TangFD
 * @since 2019/5/4.
 */
@RestController
public class IndexController {

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    public static final String BLOG_SESSION = "blog_session_Id";
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public JsonResult<String> login(@RequestBody Login login, HttpServletResponse response) {
        if (BooleanUtils.isTrue(stringRedisTemplate.hasKey(BLOG_SESSION))) {
            return new JsonResult<>("Redis", false);
        }

        if (login == null) {
            return new JsonResult<>("null", false);
        }

        if (!"admin007".equals(login.getUserName())) {
            return new JsonResult<>("n", false);
        }

        String date = DATE_FORMAT.format(new Date());
        String pwd = "Tfd" + date + ",.?";
        if (!pwd.equals(login.getPassword())) {
            return new JsonResult<>("p", false);
        }

        String sessionId = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(BLOG_SESSION, sessionId, 30, TimeUnit.MINUTES);
        return new JsonResult<>(null, sessionId, true);
    }

    @RequestMapping("/checkSession/{sessionId}")
    public JsonResult checkSession(@PathVariable("sessionId") String sessionId) {
        String id = stringRedisTemplate.opsForValue().get(BLOG_SESSION);
        if (sessionId.equals(id)) {
            return new JsonResult();
        }

        return new JsonResult("", false);
    }

    @NeedLogin
    @RequestMapping("/manage/logout")
    public void logout() {
        stringRedisTemplate.expire(BLOG_SESSION, 0, TimeUnit.SECONDS);
    }
}
